package com.gome.ss.webserver.servlet.api;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gome.ss.common.AppConfiguer;
import com.gome.ss.flowcrawl.plugin.FlowCrawlManager;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

public class FlowCrawlExtractSave extends HttpServlet {
	
	/* /spiderkit/flowcrawl_add */
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String pluginName = req.getParameter("pluginName");
		String stepID = req.getParameter("stepID");
		String config = req.getParameter("config");
		resp.setContentType("text/html;charset=gbk");
		req.setCharacterEncoding("gbk");
		
		DBObject obj = (BasicDBObject) JSON.parse(config);
		DBCollection collection = AppConfiguer.flowCrawlConfigMongo.getDB(AppConfiguer.FLOWCRAWL_DB_NAME)
				 .getCollection(AppConfiguer.FLOWCRAWL_EXTRACT_COLLECTION_NAME);
		
		BasicDBObject query = new BasicDBObject("name", pluginName);
		query.append("stepID", stepID);
		DBCursor cursor = collection.find(query);
		
		if (cursor.count() > 0) {
			while (cursor.hasNext()) {
				DBObject oldobj = cursor.next();
				collection.remove(oldobj);
			}
		}
		
		obj.removeField("_id");
		
		collection.insert(obj);
		
		resp.getWriter().print("success");
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

}
